package com.magicode.screen.settingutil;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.magicode.screen.AppContext;
import com.magicode.screen.util.FileUtil;
import com.magicode.screen.util.MethodsCompat;

import org.kymjs.kjframe.bitmap.BitmapConfig;

import java.io.File;


/**
 * 系统设置(清除缓存)
 * 
 * @author kymjs
 * 
 */
public class ClearCacheUtil {
    private Context context;
    public ClearCacheUtil(Context context){
        this.context=context;
    }
    /**
     * 计算缓存的大小
     */
    public String  caculateCacheSize() {
        long fileSize = 0;
        String cacheSize = "0KB";
        File filesDir = context.getFilesDir();
        File cacheDir = context.getCacheDir();


        fileSize += FileUtil.getDirSize(filesDir);
        fileSize += FileUtil.getDirSize(cacheDir);
        // 2.2版本才有将应用缓存转移到sd卡的功能
        if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            File externalCacheDir = MethodsCompat.getExternalCacheDir(context);
            fileSize += FileUtil.getDirSize(externalCacheDir);
//            fileSize += FileUtil.getDirSize(new File(
//                    org.kymjs.kjframe.utils.FileUtils.getSDCardPath()
//                            + File.separator + BitmapConfig.CACHEPATH));
        }
        if (fileSize > 0)
            cacheSize = FileUtil.formatFileSize(fileSize);
     return cacheSize;
    }
    /**
     * 清除app缓存
     *
     * @param activity
     */
    public static boolean clearAppCache(Activity activity) {
        boolean flag=true;
        try {
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 1) {
//                    AppContext.showToastShort("缓存清除成功");
                    } else {
                        //                   AppContext.showToastShort("缓存清除失败");
                    }
                }
            };
            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();
                    try {
                        AppContext.getInstance().clearAppCache();
                        msg.what = 1;
                    } catch (Exception e) {
                        e.printStackTrace();
                        msg.what = -1;
                    }
                    handler.sendMessage(msg);
                }
            }.start();
        }catch (Exception e){
            flag=false;
        }
        return flag;
    }

}
